package com.heima.behavior.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.behavior.service.ApUnLikeBehaviorService;
import com.heima.common.constants.ArticleBehaviorConstants;
import com.heima.common.constants.HotArticleConstants;
import com.heima.common.exception.CustomException;
import com.heima.common.redis.CacheService;
import com.heima.model.behavior.dtos.UnLikesBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.mess.UpdateArticleMess;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

/**
 * ClassName: ApLikeBehaviorServiceImpl
 * Description:
 * date: 2023/8/27 0027 16:33
 *
 * @author zHan
 */
@Service
@Slf4j
public class ApUnLikeBehaviorServiceImpl implements ApUnLikeBehaviorService {

    @Autowired
    private CacheService cacheService;

    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;

    /**
     * 不喜欢
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult unlikesBehavior(UnLikesBehaviorDto dto) {
        // 检查参数
        checkParam(dto);
        // 获取当前用户
        ApUser user = AppThreadLocalUtil.getUser();
        // 不喜欢的key
        String unlikeKey = ArticleBehaviorConstants.UNLIKE + user.getId()
                + ":" + dto.getArticleId();
        // 如果为0，不喜欢
        dto.setOperation(dto.getType());
        // 封装对象
        UpdateArticleMess updateArticleMess = new UpdateArticleMess();
        updateArticleMess.setArticleId(dto.getArticleId());
        updateArticleMess.setType(UpdateArticleMess.UpdateArticleType.LIKES);
        if (dto.getType() == 0) {
            String value = JSON.toJSONString(dto);
            cacheService.set(unlikeKey, value);
            updateArticleMess.setAdd(1);
        } else {
            // 删除不喜欢
            cacheService.delete(unlikeKey);
            updateArticleMess.setAdd(-1);
        }

        // 发送信息，数据聚合
        kafkaTemplate.send(HotArticleConstants.HOT_ARTICLE_SCORE_TOPIC,
                JSON.toJSONString(updateArticleMess));

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 检查参数
     *
     * @param dto
     */
    private void checkParam(UnLikesBehaviorDto dto) {
        if (dto.getArticleId() == null || dto.getType() == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        if (dto.getType() < 0 || dto.getType() > 1) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
    }
}
